package HomeWork;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

public class RandomCallName05 {
    private static final String FILE_Path = "src/HomeWork/rcn.txt";
    private static List<String> names;
    private static List<Double> weights;

    public static void main(String[] args) throws IOException {
        try {
            names = Files.readAllLines(Paths.get(FILE_Path));
            weights = new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                weights.add(0.1);
            }

            for (int i = 0; i < 10; i++) {
                String selectedName = getRandomName();
                System.out.println("点到的学生: " + selectedName);
                System.out.println(weights);
            }
        } catch (IOException e) {
            System.out.println("error");
        }
    }

    private static String getRandomName() {
        double totalWeight = 0.0;
        for (Double weight : weights) {
            totalWeight = totalWeight + weight;
        }
        double randomValue = new Random().nextDouble() * totalWeight;

        double cumulativeWeight = 0.0;
        int selectedIndex = -1;
        for (int i = 0; i < weights.size(); i++) {
            cumulativeWeight += weights.get(i);
            if (randomValue < cumulativeWeight) {
                selectedIndex = i;
                break;
            }
        }

        if (selectedIndex >= 0) {
            double newWeight = weights.get(selectedIndex) / 2;
            weights.set(selectedIndex, newWeight);
            return names.get(selectedIndex);
        }
        return null;
    }
}
